package com.billionsfinance.hessian.common.zookeeper.server;

import com.billionsfinance.hessian.model.ServerInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @ ClassName: ServerSideZkConnectionStateListener.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/11/23 12:33
 * @ Version: v1.0.0
 */
public class ServerSideZkConnectionStateListener implements ConnectionStateListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerSideZkConnectionStateListener.class);

    private static final Executor es = Executors.newFixedThreadPool(3);

    private Set<ServerInfo> serviceSet;

    ServerSideZkConnectionStateListener(Set<ServerInfo> servers) {
        this.serviceSet = servers;
    }

    /**
     * 开启线程池来快速注册服务
     *
     * @param curatorFramework Curator实例
     * @param serverInfo       服务端信息
     */
    private void registerSingleService(CuratorFramework curatorFramework, ServerInfo serverInfo) {
        es.execute(new ServerSideRegisterThread(curatorFramework, serverInfo));
    }

    /**
     * 注册所有扫描到的服务
     *
     * @param curatorFramework Curator实例
     */
    private void registerAllService(CuratorFramework curatorFramework) {
        for (ServerInfo model : serviceSet) {
            registerSingleService(curatorFramework, model);
        }
    }

    /**
     * 当程序连接到zookeeper时的状态发生变更时的回调方法
     *
     * @param curatorFramework Curator实例
     * @param connectionState  连接状态
     */
    @Override
    public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
        LOGGER.info("连接zookeeper的状态发生变更,当前状态为: {}", connectionState.name());
        if (ConnectionState.CONNECTED == connectionState) {
            LOGGER.info("连接zookeeper 成功 ！");
            // 注册所有服务
            registerAllService(curatorFramework);
        }
        if (ConnectionState.RECONNECTED == connectionState) {
            LOGGER.info("重新连接zookeeper 成功 ！");
            // 重新注册所有服务
            registerAllService(curatorFramework);
        }
    }
}
